package com.you.shortlink.project.dao.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.you.shortlink.project.dao.entity.LinkNetworkStatsDO;
import com.you.shortlink.project.dto.req.ShortLinkGroupStatsReqDTO;
import com.you.shortlink.project.dto.req.ShortLinkStatsReqDTO;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 访问网络统计访问持久层
 */
public interface LinkNetworkStatsMapper extends BaseMapper<LinkNetworkStatsDO> {

    /**
     * 记录访问网络监控数据
     */
    @Insert("""
            INSERT INTO t_link_network_stats (full_short_url, gid, date, cnt, network, create_time, update_time, del_flag) 
            VALUES (#{linkNetworkStats.fullShortUrl}, #{linkNetworkStats.gid}, #{linkNetworkStats.date}, #{linkNetworkStats.cnt}, #{linkNetworkStats.network}, NOW(), NOW(), 0)
            ON DUPLICATE KEY UPDATE cnt = cnt + #{linkNetworkStats.cnt};
            """)
    void shortLinkNetwork(@Param("linkNetworkStats") LinkNetworkStatsDO linkNetworkStatsDO);

    /**
     * 根据短链接获取指定日期内访问网络数据
     */
    @Select("""
            SELECT network, SUM(cnt) as cnt 
            FROM t_link_network_stats WHERE full_short_url = #{param.fullShortUrl} AND gid = #{param.gid} AND `date` BETWEEN #{param.startDate} AND #{param.endDate}
            GROUP BY full_short_url, gid, network;
            """)
    List<LinkNetworkStatsDO> listNetworkStatsByShortLink(@Param("param") ShortLinkStatsReqDTO requestParam);

    /**
     * 根据短链接分组获取指定日期内访问网络数据
     */
    @Select("""
            SELECT network, SUM(cnt) as cnt 
            FROM t_link_network_stats WHERE gid = #{param.gid} AND `date` BETWEEN #{param.startDate} AND #{param.endDate}
            GROUP BY gid, network;
            """)
    List<LinkNetworkStatsDO> listNetworkStatsByShortLinkGroup(@Param("param") ShortLinkGroupStatsReqDTO requestParam);

}
